<?php
namespace plugins\task\controller;

use cmf\controller\ApiPluginBaseController;
use think\Validate;
use app\common\lib\model_operate\Transit;
use plugins\task\model\TaskModel;

class ApiIndexController extends ApiPluginBaseController
{
    /**
     *任务管理-初始页面-数据获取
     */
	public function getData()
    {
        $param = $this->request->param();
        $page           = cmf_var_isset( $param , 'page' , 1 );
        $pagesize       = cmf_var_isset( $param , 'pagesize' , 10 );
        $search_name       = cmf_var_isset( $param , 'search_name' , '' );
        $target       = cmf_var_isset( $param , 'target' , '' );

        $data = new TaskModel();
        if (!empty($search_name)) {
            $data = $data->where('company|station_name','LIKE',"%$search_name%");
        }
        if (!empty($target)) {
            $data = $data->where('target',$target);
        }


        $admin_id=cmf_get_current_admin_id();
        // $info=$this->getIdentity();
        // $admin_id = db('member')->where('uid',$info->uid)->value('user_id');

        $user=db('user')->where('id',$admin_id)->find();

        $auth_depart=$user['auth_depart'];

        if(isset($param['depart_id']) && !empty($param['depart_id'])){
            $all_depart=db('department')->where(['is_del'=>2])->where(['id'=>['in',$auth_depart]])->select()->toArray();            
            $depart=db('department')->where('id',$param['depart_id'])->find();
            $depart_ids=$this->xiaji($all_depart,$depart['id']);
            $depart_ids[]=$depart['id'];
            $data = $data->where('station_id','IN',$depart_ids);
            //$where['stationid']=['in',$depart_ids];            
        }else{
            $data = $data->where('station_id','IN',$auth_depart);
           // $where['stationid']=['in',$auth_depart];
        }
        // if(isset($param['depart_id']) && !empty($param['depart_id'])){
        //     $all_depart=db('department')->where(['is_del'=>2])->select()->toArray();
        //     $depart=db('department')->where('id',$param['depart_id'])->find();
        //     $depart_ids=$this->xiaji($all_depart,$depart['id']);
        //     // dump($depart_ids);die();
        //     $depart_ids[]=$depart['id'];
        //     $data = $data->where('station_id','IN',$depart_ids);
        //     // $where['resid']=['in',$depart_ids];
        // }
        $info = $data->order('create_time','desc')->paginate( $pagesize , false , [ 'page'=>$page ]  )->each(function($v){
            // $v['target'] = db('target')->where('id',$v['target'])->value('name');
            // $v['start_time'] = date('Y-m-d',$v['start_time']);
            // $v['end_time'] = date('Y-m-d',$v['end_time']);
            // $v['create_time'] = date('Y-m-d',$v['create_time']);
            return $v;
        });
        //导出表格
        if(isset($param['export']) && $param['export'] == 1){
            $table = Transit::createTags('table');
            $table->export($info);
        }
        return api_json_echo(true,'',$info);
    }
    //循环查找下级组织部门
    public function xiaji($xiaji,$pid){
        
        $ret = [];//定义空数组
        //循环遍历
        foreach($xiaji as $k => $v){
            if($v['parent_id'] == $pid){//如果上级id 和当前传递的id相等插入数组
               
                unset($xiaji[$k]);//删除已经插入数组的数据不然会无限循环
                $chlidren_depart = $this->xiaji($xiaji,$v['id']);//循环剩余的内容放到它的下级

                foreach ($chlidren_depart as $key => $value) {
                    $ret[] = $value;
                }

                $ret[] = $v['id'];//赋值到数组
            }
        }
        return $ret;
    }
    /**
     *任务管理-添加页面-数据提交
     */
    public function addPost()
    {
        $param = $this->request->param();
        //数据验证
        $validate = new Validate( [
            [ 'target' , 'require' , '指标不能为空' ],
            [ 'company' , 'require' , '分子公司不能为空' ],
            [ 'station_name' , 'require' , '厂站名称不能为空' ],
            [ 'price' , 'require' , '单价（元）为空' ],
            [ 'start_time' , 'require' , '计算起始时间不能为空' ],
            [ 'end_time' , 'require' , '计算终止时间不能为空' ],
        ] );
        if( !$validate->check( $param ) ){
            return api_json_echo(false ,$validate->getError());
        }

        //后台操作人员
        $uid = cmf_get_current_admin_id();  //id
        $user_login = db('user')->where('id',$uid)->value('user_login');
        // $info=$this->getIdentity();
        // $user_login = db('member')->where('uid',$info->uid)->value('nick_name');

        $remarks       = cmf_var_isset( $param , 'remarks' , '' );
        $create_manage       = cmf_var_isset( $param , 'create_manage' , $user_login );

        //名称查重
        // $device_name = $param['device_name'];
        // $deviceNames = db('task')->column('device_name');
        // if (in_array($device_name, $deviceNames)) {
        //     return api_json_echo(false,'设备名称重复');
        // }

        //数据处理
        $start_time = $param['start_time'];
        // $start_time = strtotime($param['start_time']);
        $end_time = $param['end_time'];
        // $end_time = strtotime($param['end_time']);

        //新增
        $res = db('task')->insert( [
            'target'        =>  $param['target'],
            'company'   =>  $param['company'],
            'station_name'   =>  $param['station_name'],
            'station_id'   =>  $param['station_id'],
            'price'    =>  $param['price'],
            'start_time'    =>  $start_time,
            'end_time'    =>  $end_time,
            'remarks'    =>  $remarks,
            'create_manage'    =>  $create_manage,
            'create_time' => date('Y-m-d H:i:s',time())
        ] );
        if ($res) {
            return api_json_echo(true,'添加成功');
        }else{
            return api_json_echo(false,'添加失败');
        }
    }
    //图片上传
    public function pzUpload(){
        $param = $this->request->param();

        //模块的标识
        $module = $param['_plugin'];

        //文件夹的标识
        $info = $param['info'];

        //获取上传的文件
        $file = $_FILES['file'];    

        $res = fileUpload($file,$module,$info);

        if($res['status'] == true){
            return json(['save'=>zy_domain().$res['data'],'info'=>$info]);
        }
    }
    /**
     *任务管理-修改页面-数据获取
     */
    public function edit()
    {
        $param = $this->request->param();

        $validate = new Validate( [
            [ 'id' , 'require' , '请选择需要修改的项' ],
        ] );
        if( !$validate->check( $param ) ){
            return api_json_echo(false ,$validate->getError());
        }

        $data = db('task')->find($param['id']);
        if (empty($data)) {
            return api_json_echo(false,'数据不存在');
        }
        // $data['start_time'] = date('Y-m-d',$data['start_time']);
        // $data['end_time'] = date('Y-m-d',$data['end_time']);
        return api_json_echo(true,'',$data);
    }
    /**
     *任务管理-修改页面-数据提交
     */
    public function editPost()
    {
        $param = $this->request->param();
        //数据验证
        $validate = new Validate( [
            [ 'id' , 'require' , '请选择需要修改的项' ],
            [ 'target' , 'require' , '指标不能为空' ],
            [ 'company' , 'require' , '分子公司不能为空' ],
            [ 'station_name' , 'require' , '厂站名称不能为空' ],
            [ 'price' , 'require' , '单价（元）为空' ],
            [ 'start_time' , 'require' , '计算起始时间不能为空' ],
            [ 'end_time' , 'require' , '计算终止时间不能为空' ],
        ] );
        if( !$validate->check( $param ) ){
            return api_json_echo(false ,$validate->getError());
        }
        $remarks       = cmf_var_isset( $param , 'remarks' , '' );
        $create_manage       = cmf_var_isset( $param , 'create_manage' , '' );

        //名称查重
        // $device_name = $param['device_name'];
        // $old_name = db('task')->where('id',$param['id'])->value('device_name');
        // $deviceNames = db('task')->column('device_name');
        // if (in_array($device_name, $deviceNames) && $device_name != $old_name) {
        //     return api_json_echo(false,'设备名称重复');
        // }

        //数据处理
        $start_time = $param['start_time'];
        // $start_time = strtotime($param['start_time']);
        $end_time = $param['end_time'];
        // $end_time = strtotime($param['end_time']);

        //添加修改记录,将旧数据与新数据比对,有变动的添加修改记录
        $old_info = db('task')->find($param['id']);   //获取旧数据
        // $edit_log = $old_info['edit_log'];   //存放修改记录的变量,保留历史修改
        $edit_log = '';                         //放弃历史修改

        //后台操作人员
        $uid = cmf_get_current_admin_id();  //id
        $user_login = db('user')->where('id',$uid)->value('user_login');
        // $info=$this->getIdentity();
        // $user_login = db('member')->where('uid',$info->uid)->value('nick_name');
        // dump($user_login);die();

        //数据处理
        // $old_target = db('target')->where('id',$old_info['target'])->value('name');
        // $new_target = db('target')->where('id',$param['target'])->value('name');

        //向$edit_log添加修改记录
        ($old_info['target'] == $param['target'])?:($edit_log = $edit_log.'【'.$user_login.'将指标:'.$old_info['target'].'修改为'.$param['target'].','.date('Y-m-d H:i:s',time()).'】;');
        // ($old_info['target'] == $param['target'])?:($edit_log = $edit_log.'【'.$user_login.'将指标:'.$old_target.'修改为'.$new_target.','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['company'] == $param['company'])?:($edit_log = $edit_log.'【'.$user_login.'将分子公司:'.$old_info['company'].'修改为'.$param['company'].','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['station_name'] == $param['station_name'])?:($edit_log = $edit_log.'【'.$user_login.'将厂站名称:'.$old_info['station_name'].'修改为'.$param['station_name'].','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['price'] == $param['price'])?:($edit_log = $edit_log.'【'.$user_login.'将单价（元）:'.$old_info['price'].'修改为'.$param['price'].','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['start_time'] == $start_time)?:($edit_log = $edit_log.'【'.$user_login.'将计算起始时间:'.$old_info['start_time'].'修改为'.$param['start_time'].','.date('Y-m-d H:i:s',time()).'】;');
        // ($old_info['start_time'] == $start_time)?:($edit_log = $edit_log.'【'.$user_login.'将计算起始时间:'.date('Y-m-d',$old_info['start_time']).'修改为'.$param['start_time'].','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['end_time'] == $end_time)?:($edit_log = $edit_log.'【'.$user_login.'将计算终止时间:'.$old_info['end_time'].'修改为'.$param['end_time'].','.date('Y-m-d H:i:s',time()).'】;');
        // ($old_info['end_time'] == $end_time)?:($edit_log = $edit_log.'【'.$user_login.'将计算终止时间:'.date('Y-m-d',$old_info['end_time']).'修改为'.$param['end_time'].','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['remarks'] == $remarks)?:($edit_log = $edit_log.'【'.$user_login.'将备注:'.$old_info['remarks'].'修改为'.$remarks.','.date('Y-m-d H:i:s',time()).'】;');
        ($old_info['create_manage'] == $create_manage)?:($edit_log = $edit_log.'【'.$user_login.'将创建人:'.$old_info['create_manage'].'修改为'.$create_manage.','.date('Y-m-d H:i:s',time()).'】;');

        //修改
        $res = db('task')->where('id',$param['id'])->update([
            'target'        =>  $param['target'],
            'company'   =>  $param['company'],
            'station_name'   =>  $param['station_name'],
            'station_id'   =>  $param['station_id'],
            'price'    =>  $param['price'],
            'start_time'    =>  $start_time,
            'end_time'    =>  $end_time,
            'remarks'    =>  $remarks,
            'create_manage'    =>  $create_manage,
            'edit_log'  =>  $edit_log
        ]);
        return api_json_echo(true,'修改成功');
    }
    /**
     *任务管理-页面-数据删除
     */
    public function delete()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'id' ] ) || empty( $param [ 'id' ] ) ){
            return api_json_echo( false , '请选择要删除的项' );
        }
        if (is_array($param [ 'id' ])) 
        {
           $res = db('task')->where( 'id' , 'IN' , $param [ 'id' ] )->delete();
        }else
        {
            $res = db('task')->where('id',$param [ 'id' ])->delete();
        }
        if( !$res ){
            return api_json_echo( false , '删除失败' );
        }
        return api_json_echo( true , '删除成功' );
    }
}
